import React from 'react';
import { useRouter } from 'next/router';
import { useState } from 'react';
import axios from 'axios';
export default function Login() {
  const router = useRouter();
  const [error, setError] = useState(null);

  async function handleSubmit(event) {
    event.preventDefault();
    const formData = new FormData(event.target);
    const username = formData.get('username');
    const password = formData.get('password');

    try {
      const data = {
        username: username,
        password: password,
      };

      axios
        .post('/api/login', data)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.error(error);
          // 检查错误对象以获取更多信息
          if (error.response) {
          } else if (error.request) {
            // 请求已发出，但没有收到任何响应
            console.error(error.request);
          } else {
            // 在设置请求时触发了一个错误
            console.error('Error', error.message);
          }
        });
      // 假设登录成功时，后端会设置一个 token 或其他标识
      // 在这里处理登录成功的逻辑，例如设置 cookies 或 localStorage

      // 重定向到主页或用户试图访问的页面
      // router.push('/');
    } catch (e) {
      setError(e.message);
    }
  }
  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-6 bg-gray-100">
      <h1 className="text-3xl font-bold text-center mb-6">Login</h1>
      {error && <p className="text-red-500 text-center mb-4">{error}</p>}
      <form onSubmit={handleSubmit} className="w-full max-w-sm">
        <div className="mb-4">
          <input
            type="text"
            name="username"
            placeholder="Username"
            required
            className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500"
          />
        </div>
        <div className="mb-6">
          <input
            type="password"
            name="password"
            placeholder="Password"
            required
            className="w-full px-4 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500"
          />
        </div>
        <button
          type="submit"
          className="w-full px-4 py-2 bg-blue-500 text-white font-semibold rounded hover:bg-blue-600 focus:outline-none"
        >
          Login
        </button>
      </form>
    </div>
  );
}
